package com.example.healthcondition.security;

import io.jsonwebtoken.JwtException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final JwtTokenUtil jwtTokenUtil;

    // 构造函数注入 JwtTokenUtil，确保可以使用它来解析和验证 token
    public JwtAuthenticationFilter(JwtTokenUtil jwtTokenUtil) {
        this.jwtTokenUtil = jwtTokenUtil;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        // 从请求头中获取 Authorization 字段的 token
        String token = request.getHeader("Authorization");

        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);  // 去掉 "Bearer " 前缀

            try {
                // 使用 JwtTokenUtil 解析 token，获取用户名
                String username = jwtTokenUtil.parseToken(token);

                // 如果用户名非空且 token 没有过期
                if (username != null && !jwtTokenUtil.isTokenExpired(token)) {
                    // 创建认证对象并放入 SecurityContext 中
                    UsernamePasswordAuthenticationToken authenticationToken =
                            new UsernamePasswordAuthenticationToken(username, null, null); // 根据需要可以设置角色
                    SecurityContextHolder.getContext().setAuthentication(authenticationToken);  // 将认证信息保存到 SecurityContext
                } else {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Token is expired or invalid");
                    return;  // 退出过滤器
                }
            } catch (JwtException e) {
                // 捕获 JwtException 异常，表示 token 无效
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid token");
                return;  // 退出过滤器
            }
        }

        // 继续执行过滤链
        filterChain.doFilter(request, response);
    }
}
